<?php
namespace admin\model;

use admin\model\Model;
use admin\model\TargetModel;

class BlogModel extends Model{

    /**
     * 查询博客的数量
     */
    public function getBlogCount($params = null){
        $sql = 'SELECT COUNT(*) AS count FROM blog_info';
        if(isset($params['title'])){
            $sql.=' WHERE title LIKE :title';
            $data = $this->p_query($sql,array('title'=>'%'.$params['title'].'%'));
        }else{
            $data = $this->query($sql);
        }
        return $data;
    }
    /**
     * 查询用户博客并返回
     */
    public function getBlogAll($params = array('page' => 0,'limit' => 0)){
        $curr = ($params['page']-1)*$params['limit'];
        $sql = "SELECT blog_info.id AS blog_id,user.name AS username,blog_info.title,blog_info.blog_img,blog_info.time,blog_info.reader,blog_type.id AS type_id,blog_type.name AS type_name,blog_info.praise_count,blog_info.state 
        FROM blog_info,user,blog_type
        WHERE user.id=blog_info.user_id AND blog_info.blog_type = blog_type.id ";
        if(isset($params['title'])){
            $sql.=" AND title LIKE :title ORDER BY blog_info.id ASC LIMIT {$curr},{$params['limit']} ";
            $data = $this->p_queryAll($sql,array('title'=>'%'.$params['title'].'%'));
        }else{
            $sql.=" ORDER BY blog_info.id ASC LIMIT {$curr},{$params['limit']} ";
            $data = $this->queryAll($sql);
        }
        return $this->filter($data);
    }
    /**
     * 查询单个博客的信息
     */
    public function getBlog($params){
        $sql = "SELECT blog_info.id,user.name,blog_info.title,blog_info.outline,blog_info.content,blog_info.time,blog_info.reader,blog_info.blog_type,blog_info.praise_count,blog_info.state 
        FROM blog_info INNER JOIN user 
        WHERE user.id= blog_info.user_id AND blog_info.id = :id";
        $data = $this->p_query($sql,$params);
        if(!$data){         //判断数据是否为空，若为空跳转404页面
            header('Location:/blog_system/admin/view/404.php');
            exit();
        }
        $type = new TypeModel();
        $type_data = $type->getTypeName(array('name'=>$data['blog_type']));        //查找 类别信息
        $data['blog_type'] = $type_data['name'];
        return $this->filterGet($data);
    }
    /**
     * 数据过滤
     */
    public function filter($data){

        $len = count($data,COUNT_NORMAL);       //统计数组长度
        for($i=0;$i<$len;++$i){
            $data[$i]['time'] =  date("Y-m-d H:i",$data[$i]['time']);       //发表时间
            $data[$i]['state'] = $data[$i]['state']==='0'?'私密':'公开'; 
        }
        return $data;
    }
    //过滤获取的数据
    public function filterGet($data){
        $data['name'] = $data['name']=='admin'?'站长':$data['name'];
        $data['time'] =  date("Y-m-d H:i",$data['time']);       //发表时间
        return $data;
    }
    //发表博客
    public function publishBlog($params){
        $targets = $params['target'];
        unset($params['target']);       //删除 target 
        
        date_default_timezone_set('PRC');       //设置中国时区
        $params['time'] = time();
        $sql = "INSERT blog_info(user_id,title,outline,content,blog_img,time,blog_type,state) 
        VALUES(:user_id,:title,:outline,:content,:blog_img,:time,:blog_type,:state)" ;
        //执行插入标签方法
        $insertId = $this->p_execute($sql,$params);
        $data = [];
        if($insertId){
            try{
                $this->db->beginTransaction();      //开启事务
                for($i=0;$i<count($targets);$i++){
                    $sql2 = 'INSERT blog_target(blog_id,target) VALUES(:blog_id,:target)';
                    $this->p_execute($sql2,array('blog_id'=>$insertId,'target'=>$targets[$i]));
                }
                $this->db->commit(); 
                $data['code'] = '1';
            }catch(\PDOException $e){
                $data['code'] = '0';
                $this->db->rollBack();//事务回滚
                $sql3 = "DELETE FROM blog_info WHERE id={$insertId}";       //删除博客信息
                $this->execute($sql3);
            }
        }
        $data['id'] = $insertId;
        return $data;
    }
    //设置博客状态为私密
    public function privateBlog($params){
        $sql = 'UPDATE blog_info SET state = 0 WHERE id = :id';
        $this->p_execute($sql,$params);
        $data = [];
        $data['code'] = $this->db->num;
        return $data;
    }
    /**
     * 更新博客信息         //经过预处理操作
     */
    public function updateBlog($params){
        $sql = 'UPDATE blog_info SET title = :title,reader = :reader,blog_type = :blog_type,praise_count = :praise_count,state = :state WHERE id = :id';
        $this->p_execute($sql,$params);
        $num = $this->db->num;
        if($num == 1 ){
            $res['code'] = '1';
        }else{
            $res['code'] = '0';
        }
        return json_encode($res);
    }
    /**
     * 查询单个博客信息全部信息 
     */
    public function getBlogInfo($params){
        $sql = "SELECT title,outline,content,blog_img,blog_type,state FROM blog_info WHERE id ={$params['id']}";
        $data = $this->query($sql);

        $data['id'] = $params['id'];
        $target = new TargetModel();        //查询标签信息
        $target_data = $target->getTarget(array('id'=>$params['id']));
        $data['target'] = $target_data;

        return $data;
    }
    /**
     * 更新博客内容全部信息
     */
    public function updateBlogAll($params){


        $data = [];
        $data['code'] = 0;
        try{
            $this->db->beginTransaction();      //开启事务
            $targers = $params['target'];
            unset($params['target']);
            $sql = "UPDATE blog_info 
            SET title=:title,outline=:outline,content=:content,blog_img=:blog_img,blog_type=:blog_type,state=:state 
            WHERE id = :id ";
            $this->p_execute($sql,$params);         //更新博客信息

            $del_sql = "DELETE FROM blog_target WHERE blog_id=:id";         //删除标签信息
            $this->p_execute($del_sql,array('id'=>$params['id']));
            


            for($i=0;$i<count($targers);$i++){
                $sql2 = "INSERT blog_target(blog_id,target) VALUES(:id,:target)";
                $this->p_execute($sql2,array('id'=>$params['id'],'target'=>$targers[$i]));
            }
            //判断是否插入成功，设置返回数据
            if($this->db->num == 1 && $this->db->insertId !== null){
                $data['code'] = '1';
            }else{
                $data['code'] = '0';
            }
            $this->db->commit(); 
        }catch(\PDOException $e){
            $this->db->rollBack();//事务回滚
            $data['code'] = '0';
        }
        return $data;
    }
    /**
     * 删除博客
     */
    public function delBlog($params){
        $data = [];
        $this->db->beginTransaction();              //开启事务
        try{
            $sql1 = 'DELETE FROM blog_info WHERE id=:id';            //删除博客
            $sql2 = 'DELETE FROM blog_target WHERE blog_id=:id';     //删除标签
            $sql3 = 'DELETE FROM comment WHERE blog_id=:id';         //删除评论
            $sql4 = 'DELETE FROM comment_reply WHERE blog_id=:id';  //删除追评内容

            $this->p_execute($sql1,array('id'=>$params['blog_id']));
            $this->p_execute($sql2,array('id'=>$params['blog_id']));
            $this->p_execute($sql3,array('id'=>$params['blog_id']));
            $this->p_execute($sql4,array('id'=>$params['blog_id']));

            $this->db->commit();         //提交
            $data['code'] = 1;
        }catch(\PDOException $e){
            $this->db->rollBack();
            $data['code'] = 0;
        }
        return $data;
    }

}